package com.example.transit.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.transit.R;
import com.example.transit.base.BaseActivity;
import com.example.transit.bean.BusLineItem;
import com.example.transit.bean.BusStatusInfo;
import com.example.transit.bean.CollectionBean;
import com.example.transit.bean.HistoryBean;
import com.example.transit.bean.PhoneBean;
import com.example.transit.bean.StationInfo;
import com.example.transit.contentprovider.DbCollectionInfo;
import com.example.transit.event.CollectionEvent;
import com.example.transit.event.MaingetLineinfoEvent;
import com.example.transit.event.SearchCarlineMssEvent;
import com.example.transit.event.SpHistroyEvent;
import com.example.transit.utils.SPUtils;
import com.example.transit.utils.Util;
import com.example.transit.view.BusLineView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.IllegalFormatFlagsException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.internal.schedulers.ImmediateThinScheduler;

public class BusRunActivity extends BaseActivity implements BusLineView.OnBusStationClickListener {
    @BindView(R.id.left_br_img)
    ImageView leftBrImg;
    @BindView(R.id.title_br_tv)
    TextView titleBrTv;
    @BindView(R.id.bus_startend_tv)
    TextView busStartendTV;
    @BindView(R.id.time_br_tv)
    TextView timeBrTv;
    @BindView(R.id.detail_br_tv)
    TextView detailBrTv;
    @BindView(R.id.tv_br_change)
    TextView tvBrChange;
    @BindView(R.id.tv_br_refresh)
    TextView tvBrRefresh;
    @BindView(R.id.busline_br_bv)
    BusLineView buslineBrBv;
    @BindView(R.id.collect_img)
    ImageView collectImg;

    public String result_station = null;//站点信息从服务端获取
    public String result_busInfo = null;//车站信息从服务端获取

    List<StationInfo> stationlist = new ArrayList<>();//车站信息列表
    List<StationInfo> initStationlist = new ArrayList<>();//车站初始化信息列表
    List<StationInfo> initStationlist_filter = new ArrayList<>();//车站初始化信息列表

    //换向时更新stationlist
    List<StationInfo> changestationlist = new ArrayList<>();
    //车辆状态信息
    List<BusStatusInfo> busupStatusInfoList = new ArrayList<>();
    List<BusStatusInfo> businitStatusInfoList = new ArrayList<>();

    //自定义图形信息
    List<BusLineItem> busLineItems = new ArrayList<>();

    Handler handler;
    Context context;

    //是否是上行；
    Boolean isupline = true;


    //定位都要通过LocationManager这个类实现
    private LocationManager locationManager;
    private String provider;
    MyThread myThread = null;
    private boolean myThreadWorking = false;

    //点击状态
    public int stationClickIndex = -1;//-1表示没有点击

    //计算两点之间的距离
    Util util;
    //共享参数的key
    private String spstationkey = "result_statinfo";

    //刷新detail信息
    Timer timer;

    //手机定位信息
    PhoneBean phoneBean;
    //收藏点击
    Boolean isCollSelected = false;

    //lineNum写成动态
    String linenum;

    //模糊搜索面主页传过来的数据
    String choiceLineNum;
    //收藏数据库操作
    DbCollectionInfo dbCollectionInfo;
    CollectionBean collectionBean;
    //最近车辆在集合中的角标
    private int nearCarIndexInList;

    //手机进入时获取站点下标
    private int phoneInitIndex = -1;


    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_busrun;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        //手机信息获取
        phoneBean = PhoneBean.getInstance();

        //刷新DetailView的线程
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(2);
            }
        }, 100, 500);

        result_station = SPUtils.getStationString(getContext(), spstationkey);
        //计算两点之间的距离
        util = new Util();
        //设置自定义图像接口的监听
        buslineBrBv.setOnBusStationClickListener(BusRunActivity.this);
        //获取定位服务
        //  Log.d("may", "------------------dd " + "----------");
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取当前可用的位置控制器
        List<String> list = locationManager.getProviders(true);
        // Log.d("may", "------------------list " + list);
        if (list.contains(LocationManager.GPS_PROVIDER)) {
            //是否为GPS位置控制器
            provider = LocationManager.GPS_PROVIDER;
        } else if (list.contains(LocationManager.NETWORK_PROVIDER)) {
            //是否为网络位置控制器
            provider = LocationManager.NETWORK_PROVIDER;

        } else {
            Toast.makeText(this, "Please check if the network or GPS is open.",
                    Toast.LENGTH_LONG).show();
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            //获取当前位置，这里只用到了经纬度
            String string = "纬度为：" + location.getLatitude() + ",经度为："
                    + location.getLongitude();
            phoneBean.setPhoneLatitude((float) location.getLatitude());
            phoneBean.setPhoneLongitude((float) location.getLongitude());
            //如果车辆信息不为空，则初始化detailview；
            if (result_station != null && (!result_station.equals("")) && result_station.length() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0) {
                int phoneStaIndex = getPhoneLatelyStation();
                if (phoneStaIndex >= 0) {
                    initDetailView(phoneStaIndex);
                }
            }
        }

//绑定定位事件，监听位置是否改变
//第一个参数为控制器类型第二个参数为监听位置变化的时间间隔（单位：毫秒）
//第三个参数为位置变化的间隔（单位：米）第四个参数为位置监听器
        locationManager.requestLocationUpdates(provider, 2000, 2,
                locationListener);

        //初始化线路信息
        if (result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
            initStationlist = analyStaNameMulti(result_station, choiceLineNum, isupline); //已经自动获取上下行数组集合
            buslineBrBv.setBusLineData(initLineDataUp(initStationlist)); // 设置数据
            Log.d("may", "result_station " + result_station + initStationlist.size());
        }
        //初始化收藏数据
        dbCollectionInfo = new DbCollectionInfo(getContentResolver(), this);
        collectionBean = new CollectionBean();
        collectionBean.setIsupline(isupline);
        collectionBean.setLineNum(choiceLineNum);
        collectionBean.setName(busStartendTV.getText().toString());
        Boolean hasdata = dbCollectionInfo.Dup_check(collectionBean);
        if (hasdata) {
            isCollSelected = true;
            collectImg.setSelected(true);
        } else {
            isCollSelected = false;
            collectImg.setSelected(false);
        }
    }

    //手机定位监听
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            // 更新当前经纬度
            if (location != null) {
                phoneBean.setPhoneLatitude((float) location.getLatitude());
                phoneBean.setPhoneLongitude((float) location.getLongitude());
                if (stationClickIndex < 0) {
                    if (result_station != null && (!result_station.equals("")) && result_station.length() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0) {
                        int phoneStaIndex = getPhoneLatelyStation();
                        if (phoneStaIndex >= 0) {
                            initDetailView(phoneStaIndex);
                        }
                    }
                }
            }

        }
    };

    //获取搜索框传过来的内容
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(SearchCarlineMssEvent searchCarlineMssEvent) {
        choiceLineNum = searchCarlineMssEvent.getLineNum();
        isupline = searchCarlineMssEvent.getIsupline();
        linenum = "linenum=" + searchCarlineMssEvent.getLineNum();
        titleBrTv.setText(searchCarlineMssEvent.getLineNum());
        busStartendTV.setText(searchCarlineMssEvent.getLineStart() + "--->" + searchCarlineMssEvent.getLineEnd());
    }

    //获取最近使用fragment传过来的内容
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(SpHistroyEvent spHistroyEvent) {
        choiceLineNum = spHistroyEvent.getLineNum();
        isupline = spHistroyEvent.getIsupline();
        linenum = "linenum=" + spHistroyEvent.getLineNum();
        String historydata = spHistroyEvent.getHistorystr();
        //截取字符串显示title
        titleBrTv.setText(historydata.substring(0, historydata.indexOf("(")));
        busStartendTV.setText(historydata.substring(historydata.indexOf("(") + 1, historydata.indexOf(")")));

    }

    //获取最近使用fragment传过来的内容
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(CollectionEvent collectionEvent) {
        choiceLineNum = collectionEvent.getLineNum();
        isupline = collectionEvent.getIsupline();
        linenum = "linenum=" + collectionEvent.getLineNum();
        titleBrTv.setText(choiceLineNum);
        busStartendTV.setText(collectionEvent.getStaName());

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        context = this;
        if (!myThreadWorking) {
            myThread = new MyThread();
            Log.d("may", "initStationlist--isupline1----: run my thread ");
            myThread.start();
            myThreadWorking = true;
        }
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0://站点名字初始化操作
                        //  Log.d("may", "initStationlist--isuplinehandler0----: " + isupline);
                        // 设置公交信息
                        updatebuslineBrBv();
                        if (result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0) {
                            businitStatusInfoList = analyseBusStatus(result_busInfo);
                            //点击事件记忆
                            busLineItems.clear();
                            busLineItems = initBusDataUp(businitStatusInfoList, initStationlist);
                            if (stationClickIndex >= 0) {
                                busLineItems.get(stationClickIndex).isCurrentPosition = true;
                            }
                            buslineBrBv.setBusLineData(busLineItems);
                        }
                        buslineBrBv.invalidate();

                        break;
                    case 1://换向按钮操作
                        updatebuslineBrBv();
                        if (result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0 && result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                            busupStatusInfoList = analyseBusStatus(result_busInfo);
                            buslineBrBv.setBusLineData(initBusDataUp(busupStatusInfoList, changestationlist));
                        } else if (result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                            buslineBrBv.setBusLineData(initLineDataUp(changestationlist));
                        }
                        buslineBrBv.requestLayout();//重新获取宽高
                        buslineBrBv.invalidate();
                        break;
                    case 2:
                        if (result_busInfo == null || (result_busInfo.equals("")) || result_busInfo.length() == 0) {
                            // detailBrTv.setText("looking for busInfo. Please wait a moment...");
                        }
                        //实时更新detail信息；
                        if (businitStatusInfoList.size() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0 && result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                            if (stationClickIndex != -1) {
                                if (initStationlist.size() != 0) {
                                    upDetailView();
                                }
                            }
                        }
                        //未点击时，更新信息
                        if (stationClickIndex < 0) {
                            if (result_station != null && (!result_station.equals("")) && result_station.length() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0) {
                                int phoneStaIndex = getPhoneLatelyStation();
                                if (phoneStaIndex >= 0) {
                                    initDetailView(phoneStaIndex);
                                }

                            }
                        } else {
                            phoneInitIndex = -1;
                        }

                        break;

                }
            }
        };
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {//ctrl点播
            Intent intent = new Intent();
            intent.setClass(BusRunActivity.this, MainActivity.class);
            startActivity(intent);
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.left_br_img, R.id.title_br_tv, R.id.bus_startend_tv, R.id.time_br_tv, R.id.detail_br_tv, R.id.busline_br_bv, R.id.tv_br_change, R.id.tv_br_refresh, R.id.collect_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_br_img:
                Intent intent = new Intent(BusRunActivity.this, MainActivity.class);
                startActivity(intent);
                this.finish();
                break;
            case R.id.title_br_tv:
                break;
            case R.id.bus_startend_tv:
                break;
            case R.id.time_br_tv:
                break;
            case R.id.detail_br_tv:
                break;
            case R.id.busline_br_bv:

                break;
            case R.id.tv_br_change:

                Log.d("may", "----cynoware test CHANGE" + "-------DDDOODD");
                //点击时清掉点击站点数据
                stationClickIndex = -1;
                result_busInfo = null;
                if (result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                    if (isupline && getDownStalist(result_station, choiceLineNum).size() != 0) {
                        detailBrTv.setText("looking for busInfo. Please wait a moment.");
                        changestationlist.clear();
                        changestationlist = getDownStalist(result_station, choiceLineNum);
                        isupline = false;
                        busStartendTV.setText(changestationlist.get(0).getStationName() + "--->" + changestationlist.get(changestationlist.size() - 1).getStationName());
                        handler.sendEmptyMessage(1);
                    } else if (isupline && getDownStalist(result_station, choiceLineNum).size() == 0) {
                        Toast.makeText(this, "No reverse information", Toast.LENGTH_LONG).show();

                    } else if ((!isupline) && getUpStalist(result_station, choiceLineNum).size() != 0) {
                        detailBrTv.setText("looking for busInfo. Please wait a moment.");
                        changestationlist.clear();
                        changestationlist = getUpStalist(result_station, choiceLineNum);
                        isupline = true;
                        busStartendTV.setText(changestationlist.get(0).getStationName() + "--->" + changestationlist.get(changestationlist.size() - 1).getStationName());
                        handler.sendEmptyMessage(1);
                    } else if ((!isupline) && getUpStalist(result_station, choiceLineNum).size() == 0) {
                        Toast.makeText(this, "No reverse information", Toast.LENGTH_LONG).show();

                    }
                    //改变时反向更新数据
                }

                //初始化收藏数据
                collectionBean = new CollectionBean();
                collectionBean.setIsupline(isupline);
                collectionBean.setLineNum(choiceLineNum);
                collectionBean.setName(busStartendTV.getText().toString());
                Boolean hasdata = dbCollectionInfo.Dup_check(collectionBean);
                //  Log.d("may", " hasdata:" + hasdata+" isupline:"+isupline+" choiceLineNum:"+choiceLineNum+" busStartendTV.getText().toString():"+busStartendTV.getText().toString());
                if (hasdata) {
                    collectImg.setSelected(true);
                } else {
                    collectImg.setSelected(false);
                }


                break;
            case R.id.tv_br_refresh:
                updatebuslineBrBv();
                Toast.makeText(this, "Refreshing。。。。", Toast.LENGTH_LONG).show();
                break;

            case R.id.collect_img:
                //注意初始状态是false走的else方法，点击进入后插入数据
                if (isCollSelected) {
                    //查询数据库看是否有之前的记录
                    isCollSelected = false;
                    if (dbCollectionInfo.Dup_check(collectionBean)) {
                        dbCollectionInfo.deleteCollect(collectionBean);
                    }

                } else {
                    isCollSelected = true;
                    if (!dbCollectionInfo.Dup_check(collectionBean)) {
                        dbCollectionInfo.insertCollectInfo(collectionBean);
                    }

                }
                collectImg.setSelected(isCollSelected);

        }
    }
    //获取服务端车辆信息数据方法

    public String httpGetBusInfo(String server, String cookie) {
        String jsons = null;
        String httpUrl = server;
        URL url;
        try {
            url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setRequestMethod("GET");
            if (cookie != null)
                conn.setRequestProperty("Cookie", cookie);
            conn.setRequestProperty("Content-Language", "zh-cn");
            conn.setRequestProperty("Connection", "keep-alive");
            InputStream input = conn.getInputStream();
            InputStreamReader inputreader = new InputStreamReader(input);
            BufferedReader reader = new BufferedReader(inputreader);
            String str = null;
            StringBuffer sb = new StringBuffer();
            while ((str = reader.readLine()) != null) {
                sb.append(str).append("\n");
            }
            if (sb != null) {
                jsons = sb.toString();
            }
            reader.close();
            inputreader.close();
            input.close();
            conn.disconnect();
            input = null;
            inputreader = null;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            Log.e("busappmas", "http get error URLException");
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("busappmas", "http get error IOException");
            return null;
        } catch (Exception e) {
            Log.e("busappmas", "http get error Exception");
            return null;
        }
        return jsons;
    }


    //设置公交站点名称
    private List<BusLineItem> initLineDataUp(List<StationInfo> stationlist) {
        ArrayList<BusLineItem> list = new ArrayList<>();
        for (int i = 0; i < stationlist.size(); i++) {
            BusLineItem item = new BusLineItem();
            if (stationlist.get(i).getIsRealStation().equals("0")) {
                item.isRealStation = false;
            }

            item.name = stationlist.get(i).getStationName();
            list.add(item);
        }
        return list;
    }

    //更新化公交车数据
    private List<BusLineItem> initBusDataUp(List<BusStatusInfo> busStatusInfoList, List<StationInfo> stationlist) {
        //为最近的一辆车添加标注
        ArrayList<BusLineItem> list = new ArrayList<>();
        for (int i = 0; i < stationlist.size(); i++) {
            BusLineItem item = new BusLineItem();
            //判断虚拟站点
            if (stationlist.get(i).getIsRealStation().equals("0")) {
                item.isRealStation = false;
            }
            if (phoneInitIndex != -1) {
                if (i == phoneInitIndex) {
                    item.isCurrentPosition = true;
                }
            }
            item.name = stationlist.get(i).getStationName();
            for (int b = 0; b < busStatusInfoList.size(); b++) {
                if (busStatusInfoList.get(b).getPreStationOrder() != null) {//判断为空时会报错
                    int currentSt = Integer.parseInt(busStatusInfoList.get(b).getPreStationOrder()) - 1;//判断当前车辆在图上哪个位置
                    //判断有辆车时最小距离
                    if (i == currentSt && stationlist.size() > 1 && i + 1 < stationlist.size()) {
                        //两站之间的距离；
                        float stationdistance = getDistance(stationlist.get(i).getLinelatitude(), stationlist.get(i).getLinelongitude(), stationlist.get(i + 1).getLinelatitude(), stationlist.get(i + 1).getLinelongitude());
                        int cposition = (int) (busStatusInfoList.get(b).getPreStationDistance() / stationdistance * 100);
                        item.busPosition = cposition;
                        item.busNum += 1;
                        //给最近的车辆加标记
                        if (nearCarIndexInList != -1 && b == nearCarIndexInList) {
                            item.isNearCar = true;

                        }
                    }
                }
            }
            list.add(item);
        }
        return list;
    }

    //获取两点之间的距离
    public Float getDistance(double lat1, double lon1, double lat2, double lon2) {
        float[] results = new float[1];
        Location.distanceBetween(lat1, lon1, lat2, lon2, results);
        return results[0];
    }

    //初始化公交车数据
    private List<BusLineItem> initBusData() {
        ArrayList<BusLineItem> list = new ArrayList<>();
        for (int i = 0; i < stationlist.size(); i++) {
            BusLineItem item = new BusLineItem();
            item.name = stationlist.get(i).getStationName();
            if (i == 6 || i == 10 || i == 13) {
                //   item.isRailwayStation = true;
                item.busPosition = 0;
            }
            if (i == 7) {
                //  item.isCurrentPosition = true;//设置当前到达哪个站
                //   item.busPosition = 0;//设置公交车离当前站点距离，为0的话，公交车用大图标表示就是画上一辆公交
            }
            list.add(item);
        }
        return list;
    }

    //刷新画布
    private void updatebuslineBrBv() {
        buslineBrBv.requestLayout();
        buslineBrBv.invalidate();
    }

    //解析服务端传送的公交状态信息
    public List<BusStatusInfo> analyseBusStatus(String resStr) {
        businitStatusInfoList.clear();
        busupStatusInfoList.clear();
        resStr = resStr.trim();
        List<BusStatusInfo> list = new ArrayList<>();
        String[] data = resStr.split("<br/>");
        for (int i = 0; i < data.length; i++) {
            BusStatusInfo info = new BusStatusInfo();
            String datainfo = data[i].trim();
            String[] dataitems = datainfo.split(" ");
            if (dataitems.length == 5) {
                Log.d("may", "buost: " + dataitems.length + "/n");
                info.setBusName(dataitems[0]);
                info.setPreStationOrder(dataitems[1]);
                info.setPreStationDistance(Float.parseFloat(dataitems[2]));
                info.setLongitude(Float.parseFloat(dataitems[3]));
                info.setLatitude(Float.parseFloat(dataitems[4]));
            }
            list.add(info);
        }

        return list;
    }

    //解析服务端传送的线路名称信息
    public List<StationInfo> analyStaNameMulti(String resStr, String linenum, Boolean isupline) {
        stationlist.clear();
        resStr = resStr.trim();
        String[] data = resStr.split("\n");
        for (int i = 0; i < data.length; i++) {
            StationInfo info = new StationInfo();
            String datainfo = data[i].trim();
            String[] dataitems = datainfo.split("\\^#");
            if (isupline && dataitems[5].equals("1") && dataitems[0].equals(linenum)) {
                info.setLineNum(dataitems[0]);
                info.setStationName(dataitems[9]);
                info.setLinelongitude(Float.parseFloat(dataitems[3]));
                info.setLinelatitude(Float.parseFloat(dataitems[4]));
                info.setIsupline(isupline);
                info.setLineStationOrder(dataitems[6]);
                info.setIsRealStation(dataitems[8]);
                info.setNext_distance(Float.parseFloat(dataitems[11]));
                stationlist.add(info);

            } else if (!isupline && dataitems[5].equals("0") && dataitems[0].equals(linenum)) {
                info.setLineNum(dataitems[0]);
                info.setStationName(dataitems[1]);
                info.setLinelongitude(Float.parseFloat(dataitems[3]));
                info.setLinelatitude(Float.parseFloat(dataitems[4]));
                info.setIsupline(isupline);
                info.setLineStationOrder(dataitems[6]);
                info.setIsRealStation(dataitems[8]);
                info.setNext_distance(Float.parseFloat(dataitems[11]));
                stationlist.add(info);
            }

        }
        return getInitStationlist_filter(stationlist);
    }

    //写一个算法计算虚拟站点：
    private List<StationInfo> getInitStationlist_filter(List<StationInfo> stationlist) {
        initStationlist_filter.clear();
        int num_infpoint = 0;
        for (int i = 0; i < stationlist.size(); i++) {
            if (stationlist.get(i).getIsRealStation().equals("1")) {
                StationInfo info = new StationInfo();
                info.setLineNum(stationlist.get(i).getLineNum());
                info.setStationName(stationlist.get(i).getStationName());
                info.setLinelongitude(stationlist.get(i).getLinelongitude());
                info.setLinelatitude(stationlist.get(i).getLinelatitude());
                info.setIsupline(stationlist.get(i).getIsupline());
                info.setLineStationOrder(String.valueOf(Integer.parseInt(stationlist.get(i).getLineStationOrder()) - num_infpoint));
                info.setIsRealStation(stationlist.get(i).getIsRealStation());
                info.setNext_distance(stationlist.get(i).getNext_distance());
                initStationlist_filter.add(info);
            } else {
                num_infpoint += 1;
                initStationlist_filter.get(i - num_infpoint).setNext_distance(initStationlist_filter.get(i - num_infpoint).
                        getNext_distance() + stationlist.get(i).getNext_distance());

            }
        }
        for (int i = 0; i < initStationlist_filter.size(); i++) {
            Log.d("---lai", "lai_" + i + initStationlist_filter.get(i).getStationName() + "----" + initStationlist_filter.get(i).getLineStationOrder() + ":站:" + initStationlist_filter.get(i).getNext_distance());
        }
        return initStationlist_filter;

    }

    //获取下行数据
    public List<StationInfo> getDownStalist(String resStr, String linenum) {
        changestationlist.clear();
        resStr = resStr.trim();
        List<StationInfo> list = new ArrayList<>();
        String[] data = resStr.split("\n");
        for (int i = 0; i < data.length; i++) {
            StationInfo info = new StationInfo();
            String datainfo = data[i].trim();
            String[] dataitems = datainfo.split("\\^#");
            //上行数据集合
            if (dataitems[5].equals("0") && dataitems[0].equals(linenum)) {
                info.setLineNum(dataitems[0]);
                info.setStationName(dataitems[9]);
                info.setLinelongitude(Float.parseFloat(dataitems[3]));
                info.setLinelatitude(Float.parseFloat(dataitems[4]));
                info.setIsupline(false);
                info.setLineStationOrder(dataitems[6]);
                info.setIsRealStation(dataitems[8]);
                info.setNext_distance(Float.parseFloat(dataitems[11]));
                list.add(info);
            }
        }

        return getInitStationlist_filter(list);
    }

    //获取上行行数据
    public List<StationInfo> getUpStalist(String resStr, String linenum) {
        changestationlist.clear();
        resStr = resStr.trim();
        List<StationInfo> list = new ArrayList<>();
        String[] data = resStr.split("\n");
        for (int i = 0; i < data.length; i++) {
            StationInfo info = new StationInfo();
            String datainfo = data[i].trim();
            String[] dataitems = datainfo.split("\\^#");
            //上行数据集合
            if (dataitems[5].equals("1") && dataitems[0].equals(linenum)) {
                info.setLineNum(dataitems[0]);
                info.setStationName(dataitems[9]);
                info.setLinelongitude(Float.parseFloat(dataitems[3]));
                info.setLinelatitude(Float.parseFloat(dataitems[4]));
                info.setIsupline(true);
                info.setLineStationOrder(dataitems[6]);
                info.setIsRealStation(dataitems[8]);
                info.setNext_distance(Float.parseFloat(dataitems[11]));
                list.add(info);
            }

        }
        return getInitStationlist_filter(list);
    }

    //在子线程中获取网络数据
    public class MyThread extends Thread {
        int moni = 0;

        public void run() {
            while (myThreadWorking) {
                try {

                    //获取公交信息
                    //证方向出来
                    String forward = "direction=" + "1";
                    String reverse = "direction=" + "0";
                    String busInfoSever;
                    // Log.d("may", "result_station++++- " + "--880099--------" + result_station);
                    if (result_station != null && (!result_station.equals("")) && result_station.length() != 0 && (!linenum.equals("")) && linenum != null) {
                        //  Log.d("may", "initStationlist-------: " + result_station);
                        Log.d("may", "initStationlist--isupline1----: " + isupline);
                        if (isupline) {
                            initStationlist.clear();
                            initStationlist = getUpStalist(result_station, choiceLineNum);
                            result_busInfo = null;
                            if ((!SPUtils.getConfigserverString(getContext(), "server").equals("")) && (!SPUtils.getConfigserverString(getContext(), "port").equals("")) && (!SPUtils.getConfigserverString(getContext(), "subserver").equals(""))) {
                                String basefserver = "http://" + SPUtils.getConfigserverString(getContext(), "server") + ":" + SPUtils.getConfigserverString(getContext(), "port") + "/" + SPUtils.getConfigserverString(getContext(), "subserver") + "/";
                                busInfoSever = basefserver + "GetDeviceInfos?" + linenum + "&" + forward;
                            } else {
                                busInfoSever = "http://122.112.241.174:10085/Busyingni/GetDeviceInfos?" + linenum + "&" + forward;
                            }

                            result_busInfo = httpGetBusInfo(busInfoSever, null);
                        } else {
                            initStationlist.clear();
                            initStationlist = getDownStalist(result_station, choiceLineNum);
                            result_busInfo = null;
                            if ((!SPUtils.getConfigserverString(getContext(), "server").equals("")) && (!SPUtils.getConfigserverString(getContext(), "port").equals("")) && (!SPUtils.getConfigserverString(getContext(), "subserver").equals(""))) {
                                String baserserver = "http://" + SPUtils.getConfigserverString(getContext(), "server") + ":" + SPUtils.getConfigserverString(getContext(), "port") + "/" + SPUtils.getConfigserverString(getContext(), "subserver") + "/";
                                busInfoSever = baserserver + "GetDeviceInfos?" + linenum + "&" + reverse;
                            } else {
                                busInfoSever = "http://122.112.241.174:10085/Busyingni/GetDeviceInfos?" + linenum + "&" + reverse;
                            }
                            result_busInfo = httpGetBusInfo(busInfoSever, null);

                        }
                        Log.d("may", "busInfoSever-------: " + busInfoSever);
                        //                Log.d("may", "initStationlist: " + initStationlist.size());
                        result_busInfo = "v0319 " + "5" + " 20.08795 50.047002 26.573587<br/>" + "v0319 " + "5" + " 20.08795 50.047002 26.573587<br/>" + "v0319 " + (++moni) + " 0.00 50.047002 26.573587<br/>";
                        if (moni == 14) moni = 0;

                        handler.sendEmptyMessage(0);
                    }
                    //Thread.sleep(20*1000);
                    Thread.sleep(3 * 1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        }
    }

    //初次进来获取手机离站点最近的位置
    private int getPhoneLatelyStation() {
        List<Float> latelyStaList = new ArrayList<>();
        if (result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
            for (int i = 0; i < initStationlist.size(); i++) {
                float phoneDisToSta = getDistance(phoneBean.getPhoneLatitude(), phoneBean.getPhoneLongitude(), initStationlist.get(i).getLinelatitude(), initStationlist.get(i).getLinelongitude());
                latelyStaList.add(Math.abs(phoneDisToSta));//取距离的绝对值
            }
            if (latelyStaList.size() != 0) {
                float minPhoToSta = latelyStaList.get(0);
                int minIndex = 0;
                for (int i = 0; i < latelyStaList.size(); i++) {
                    if (latelyStaList.get(i) < minPhoToSta) {
                        minPhoToSta = latelyStaList.get(i);
                        minIndex = i;
                    }

                }
                return minIndex;

            }
        }
        return -1;

    }

    //获取手机初次进来时车辆距离最近站点的距离信息
    private void initDetailView(int stationIndex) {
        if (initStationlist.size() != 0 && initStationlist != null) {
            float currstLongitude = initStationlist.get(stationIndex).getLinelongitude();
            float currstlatitude = initStationlist.get(stationIndex).getLinelatitude();
            List<BusStatusInfo> disStationlist = new ArrayList<>();
            List<BusStatusInfo> maxorderdisStationlist = new ArrayList<>();
            disStationlist.clear();
            maxorderdisStationlist.clear();
            if (businitStatusInfoList.size() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0 && result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                for (int i = 0; i < businitStatusInfoList.size(); i++) {
                    int minOrder = -1;
                    if (businitStatusInfoList.get(i).getPreStationOrder() != null) {
                        minOrder = Integer.parseInt(businitStatusInfoList.get(i).getPreStationOrder());
                    }
                    if (minOrder < stationIndex + 1) {
                        BusStatusInfo busStatusInfo = new BusStatusInfo();
                        float buslatitude = businitStatusInfoList.get(i).getLatitude();
                        float buslongitude = businitStatusInfoList.get(i).getLongitude();
                        float bustostatdis = getDistance(buslatitude, buslongitude, currstlatitude, currstLongitude);
                        busStatusInfo.setIndexInlist(i);
                        busStatusInfo.setLongitude(buslongitude);
                        busStatusInfo.setLatitude(buslatitude);
                        busStatusInfo.setDisFromCurrentSt(bustostatdis);
                        busStatusInfo.setPreStationOrder(businitStatusInfoList.get(i).getPreStationOrder());
                        disStationlist.add(busStatusInfo);
                    }
                }
                if (disStationlist != null && disStationlist.size() != 0) {

                    // 保留按照上一站距离判断最小的接口
                    int maxOrder = Integer.parseInt(disStationlist.get(0).getPreStationOrder());
                    for (int i = 0; i < disStationlist.size(); i++) {
                        if (Integer.parseInt(disStationlist.get(i).getPreStationOrder()) > maxOrder) {
                            maxOrder = Integer.parseInt(disStationlist.get(i).getPreStationOrder());
                        }
                    }

                    for (int i = 0; i < disStationlist.size(); i++) {
                        if (Integer.parseInt(disStationlist.get(i).getPreStationOrder()) == maxOrder) {
                            maxorderdisStationlist.add(disStationlist.get(i));
                        }
                    }
                    int minIndex = 0;
                    float maxdista = maxorderdisStationlist.get(0).getPreStationDistance();
                    for (int i = 0; i < maxorderdisStationlist.size(); i++) {
                        if (maxorderdisStationlist.get(i).getPreStationDistance() > maxdista) {
                            maxdista = maxorderdisStationlist.get(i).getPreStationDistance();
                            minIndex = i;
                        }
                    }
                    if (maxorderdisStationlist.size() != 0 && initStationlist.get(stationIndex) != null && initStationlist != null && initStationlist.size() != 0) {
                        int leftstation = stationIndex + 1 - Integer.parseInt(maxorderdisStationlist.get(minIndex).getPreStationOrder());
                        //用站点实现
                        int buslocIndex = Integer.parseInt(maxorderdisStationlist.get(minIndex).getPreStationOrder()) - 1;
                        float busToSta = 0;
                        busToSta = 0;
                        for (int i = buslocIndex; i < stationIndex; i++) {
                            if ((i + 1) < initStationlist.size()) {
                                busToSta += getDistance(initStationlist.get(i).getLinelatitude(), initStationlist.get(i).getLinelongitude(), initStationlist.get(i + 1).getLinelatitude(), initStationlist.get(i + 1).getLinelongitude());
                            }
                        }
                        busToSta = busToSta - maxorderdisStationlist.get(minIndex).getPreStationDistance();
                        String metersExpress = util.getKilometre(getContext(), busToSta);
                        //手机进入的时候加标记位
                        phoneInitIndex = stationIndex;
                        // String metersExpress = util.getDistance(getContext(), maxorderdisStationlist.get(minIndex).getLatitude(), maxorderdisStationlist.get(minIndex).getLongitude(), currstlatitude, currstLongitude);
                        if (initStationlist.size() != 0) {
                            detailBrTv.setText("Nearest car to " + initStationlist.get(stationIndex).getStationName() + " have " + leftstation + " station，" + metersExpress);

                            //获取最近车辆的角标
                        }
                        nearCarIndexInList = maxorderdisStationlist.get(minIndex).getIndexInlist();

                    }
                } else {
                    detailBrTv.setText("The bus have already passed the station.");
                    nearCarIndexInList = -1;

                }
            }
        }
    }

    //更新车辆信息
    private void upDetailView() {
        if (initStationlist.size() != 0 && initStationlist != null) {
            float currstLongitude = initStationlist.get(stationClickIndex).getLinelongitude();
            float currstlatitude = initStationlist.get(stationClickIndex).getLinelatitude();
            List<BusStatusInfo> disStationlist = new ArrayList<>();
            List<BusStatusInfo> maxorderdisStationlist = new ArrayList<>();
            maxorderdisStationlist.clear();
            disStationlist.clear();
            if (businitStatusInfoList.size() != 0 && result_busInfo != null && (!result_busInfo.equals("")) && result_busInfo.length() != 0 && result_station != null && (!result_station.equals("")) && result_station.length() != 0) {
                for (int i = 0; i < businitStatusInfoList.size(); i++) {
                    int minOrder = Integer.parseInt(businitStatusInfoList.get(i).getPreStationOrder());
                    if (minOrder < stationClickIndex + 1) {
                        BusStatusInfo busStatusInfo = new BusStatusInfo();
                        float buslatitude = businitStatusInfoList.get(i).getLatitude();
                        float buslongitude = businitStatusInfoList.get(i).getLongitude();
                        float bustostatdis = getDistance(buslatitude, buslongitude, currstlatitude, currstLongitude);
                        busStatusInfo.setIndexInlist(i);
                        busStatusInfo.setLongitude(buslongitude);
                        busStatusInfo.setLatitude(buslatitude);
                        busStatusInfo.setDisFromCurrentSt(bustostatdis);
                        busStatusInfo.setPreStationDistance(businitStatusInfoList.get(i).getPreStationDistance());
                        busStatusInfo.setPreStationOrder(businitStatusInfoList.get(i).getPreStationOrder());
                        disStationlist.add(busStatusInfo);
                    }
                }
                if (disStationlist != null && disStationlist.size() != 0) {
                    // 保留按照上一站距离判断最小的接口
                    int maxOrder = Integer.parseInt(disStationlist.get(0).getPreStationOrder());
                    for (int i = 0; i < disStationlist.size(); i++) {
                        if (Integer.parseInt(disStationlist.get(i).getPreStationOrder()) > maxOrder) {
                            maxOrder = Integer.parseInt(disStationlist.get(i).getPreStationOrder());
                        }
                    }

                    for (int i = 0; i < disStationlist.size(); i++) {
                        if (Integer.parseInt(disStationlist.get(i).getPreStationOrder()) == maxOrder) {
                            maxorderdisStationlist.add(disStationlist.get(i));
                        }
                    }
                    int minIndex = 0;
                    float maxdista = maxorderdisStationlist.get(0).getPreStationDistance();
                    for (int i = 0; i < maxorderdisStationlist.size(); i++) {
                        if (maxorderdisStationlist.get(i).getPreStationDistance() > maxdista) {
                            maxdista = maxorderdisStationlist.get(i).getPreStationDistance();
                            minIndex = i;
                        }
                    }
                    if (maxorderdisStationlist.size() != 0 && initStationlist != null && initStationlist.size() != 0) {
                        int leftstation = stationClickIndex + 1 - Integer.parseInt(maxorderdisStationlist.get(minIndex).getPreStationOrder());
                        //用站点计算距离公交车距离
                        int buslocIndex = Integer.parseInt(maxorderdisStationlist.get(minIndex).getPreStationOrder()) - 1;
                        int clickStaIndex = Integer.parseInt(initStationlist.get(stationClickIndex).getLineStationOrder()) - 1;
                        float busToSta = 0;
                        for (int i = buslocIndex; i < clickStaIndex; i++) {
                            busToSta += getDistance(initStationlist.get(i).getLinelatitude(), initStationlist.get(i).getLinelongitude(), initStationlist.get(i + 1).getLinelatitude(), initStationlist.get(i + 1).getLinelongitude());
                        }
                        busToSta = busToSta - maxorderdisStationlist.get(minIndex).getPreStationDistance();
                        String metersExpress = util.getKilometre(getContext(), busToSta);
                        detailBrTv.setText("Nearest car to " + initStationlist.get(stationClickIndex).getStationName() + " have " + leftstation + " station，" + metersExpress);
                        //获取最近车辆的角标
                        nearCarIndexInList = maxorderdisStationlist.get(minIndex).getIndexInlist();
                    }
                } else {
                    detailBrTv.setText("The bus have already passed the station.");
                    nearCarIndexInList = -1;

                }
            }
        }
    }


    @Override
    public void onBusStationClick(View view, BusLineItem item, int itemIndex) {
        item.isCurrentPosition = true;
        stationClickIndex = itemIndex;
        phoneInitIndex = -1;

        upDetailView();
    }

    //停止刷新自定义的线程
    private void stopTimer() {
        if (timer != null) {
            timer.cancel();
            // 一定设置为null，否则定时器不会被回收
            timer = null;
        }
    }
//添加位置监听

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationManager != null) {
            // 关闭程序时将监听器移除
            locationManager.removeUpdates(locationListener);
        }
        stopTimer();
        if (myThreadWorking) {
            if (myThread != null && myThread.isAlive()) {
                myThread.interrupt();
                myThread = null;
            }
            myThreadWorking = false;
        }
    }
}

